//
//  MyConCernViewController.m
//  HZHome
//
//  Created by SunShine on 13-10-17.
//  Copyright (c) 2013年 xzysun. All rights reserved.
//

#import "MyConCernViewController.h"
#import "MyConcernConfigCell.h"
#import "MyConcernConfigButtonCell.h"
#import "MyConcernNewsDetailViewController.h"
#import "MyConcernNoticesDetailViewController.h"
#import "PolicyFileItem.h"
#import "MyConcernFileViewController.h"
#import "MyConcernConfigListViewController.h"
#import "PolicyFileDetailViewController.h"
#import "SegmentView.h"
#import "SearchView.h"
#import "NewsMadeViewController.h"


@interface MyConCernViewController ()<SegmentViewDelegate,SearchViewDelegate>
{
    int selectIndex;
}
@property (strong, nonatomic) CustomPullToRefresh *ptr;
@property (strong, nonatomic) MyConcernDataService *dataService;
@property (assign, nonatomic) BOOL onSaving;
@property (strong, nonatomic) SearchView *searchView;

-(void)refreshView;
@end

@implementation MyConCernViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"我的关注";
    self.dataService = [[MyConcernDataService alloc]init];
    _dataService.delegate = self;
    _searchBar.inputAccessoryView = [self getInputAccessoryView];
    //开启下拉刷新
    self.ptr = [[CustomPullToRefresh alloc]initWithScrollView:self.tableView delegate:self];
    self.onSaving = NO;
    //init segment

    
    
    NSArray *array = @[@{@"image":@"海珠动态",@"light":@"海珠动态_选中"},
                       @{@"image":@"通知公告",@"light":@"通知公告_选中"},
                       @{@"image":@"人事招考",@"light":@"人事招考_选中"},
                       @{@"image":@"活动预告",@"light":@"活动预告_选中"}];
    
    SegmentView *segmentView = [[SegmentView alloc] initWithFrame:CGRectMake(0, 0, 320, 29)];
    segmentView.delegate = self;
    [segmentView initView:array];
    [self.view addSubview:segmentView];
    
    self.searchView = [SearchView initView];
    self.searchView.delegate = self;
    [self.searchView setFrame:CGRectMake(0, 29, 320, 43)];
    [self.view addSubview:self.searchView];
    self.searchView.hidden = YES;
    self.navigationItem.rightBarButtonItem = rightNavButton(self, @selector(rightNavButton), @"信息定制");
    
    [self segmentChangedAction:nil];
    //    [_tableView reloadData];
    
    [self.configTableView setBackgroundView:nil];
    [self.configTableView setBackgroundColor:[UIColor clearColor]];
    
    [self.tableView setBackgroundView:nil];
    [self.tableView setBackgroundColor:[UIColor clearColor]];
    
}

- (void)rightNavButton
{
    NewsMadeViewController *vc = [[NewsMadeViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
//    [self refreshView];

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)didSearchText:(NSString *)text
{
    _tableView.scrollEnabled = YES;
    [self startLoadingView];
    NSArray *array = @[@"'招标通告','其他通知'",@"'人事招考'",@"'活动预告'"];
    [_dataService loadNoticeMoreDataWithKey:array[selectIndex-1] title:text];
}

- (void)didSelectSegmentAtIndex:(int)index
{
    selectIndex = index;
    self.onSaving = NO;
    [self refreshView];
    _searchBar.text = @"";
    //告诉服务当前选择了哪个标签
    [_dataService selectSegmentBarAtIndex:selectIndex == 0 ? 0 : 1];
//    if (selectIndex == 3) {
//        _tableView.scrollEnabled = NO;//信息定制的界面是不允许滚动的
//        _dataService.dataList = nil;//清理数据源
//        [_tableView reloadData];
//        [_configTableView reloadData];
//    }
    if (index == 0) {
        self.searchView.hidden = YES;
        [_dataService loadDataWithKey:nil];
    } else {
        _tableView.scrollEnabled = YES;
        [self startLoadingView];
        //        [_dataService loadDataWithKey:nil];
        NSArray *array = @[@"'招标通告','其他通知'",@"'人事招考'",@"'活动预告'"];
        [_dataService loadNoticeMoreDataWithKey:array[selectIndex-1] title:nil];
        
        //        [_dataService loadNoticeMoreDataWithKey:@"人事招考" title:nil];
        [_tableView reloadData];
    }
    self.searchView.textField.text = @"";


}

#pragma mark - Segment Method
- (IBAction)segmentChangedAction:(id)sender
{
    UIButton *btn = sender;
    selectIndex = btn.tag;
    btn.selected = YES;
    self.onSaving = NO;
    [self refreshView];
    _searchBar.text = @"";
    //告诉服务当前选择了哪个标签
    [_dataService selectSegmentBarAtIndex:btn.tag];
    if (btn.tag == 3) {
        _tableView.scrollEnabled = NO;//信息定制的界面是不允许滚动的
        _dataService.dataList = nil;//清理数据源
        [_tableView reloadData];
        [_configTableView reloadData];
    } else {
        _tableView.scrollEnabled = YES;
        [self startLoadingView];
        [_dataService loadDataWithKey:nil];
        [_tableView reloadData];
    }
}

-(void)refreshView
{
    if (selectIndex == 0 ) {
        //需要隐藏搜索框
        if (!self.searchView.hidden) {
            self.searchView.hidden = YES;
            CGRect tableRect = _tableView.frame;
            tableRect.origin.y = tableRect.origin.y - 44.0f;
            tableRect.size.height = tableRect.size.height + 44.0f;
            _tableView.frame = tableRect;
        }
    } else {
        //需要显示搜索框
        if (self.searchView.hidden) {
            self.searchView.hidden = NO;
            CGRect tableRect = _tableView.frame;
            tableRect.origin.y = tableRect.origin.y + 44.0f;
            tableRect.size.height = tableRect.size.height - 44.0f;
            _tableView.frame = tableRect;
        }
    }
//    if (selectIndex == 3) {
//        //定制页面使用单独的tableView
//        self.searchView.hidden = YES;
//        _tableView.hidden = YES;
//        _configTableView.hidden = NO;
//    } else {
        _configTableView.hidden = YES;
        _tableView.hidden = NO;
//    }
}

#pragma mark - Search Bar Delegate
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    NSLog(@"search button clicked with input:%@",searchBar.text);
    [searchBar resignFirstResponder];
}

-(void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
    NSLog(@"search bar end edit with input %@",searchBar.text);
    [self startLoadingView];
    if (searchBar.text.length == 0) {
        //如果没输入内容并且点击完成，则重新刷新列表
        [self.dataService loadDataWithKey:nil];
    } else {
        [self.dataService loadDataWithKey:searchBar.text];
    }
}

#pragma mark - Table Method
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
    //其他都只有1个section
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataService.dataList.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [_dataService heightForCellAtRow:indexPath];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell;
    if (selectIndex == 0) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"ImportantNewsCell" owner:self options:nil] objectAtIndex:0];
    } else  {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"NoticesCell" owner:self options:nil] objectAtIndex:0];
    }
    [cell setBackgroundColor:[UIColor clearColor]];
    [_dataService configCell:cell atIndex:indexPath];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (selectIndex == 0) {
        //要情动态
        MyConcernNewsDetailViewController *detailVC = [[MyConcernNewsDetailViewController alloc]initWithNibName:@"MyConcernNewsDetailViewController" bundle:nil];
        detailVC.config = [NSDictionary dictionaryWithObjectsAndKeys:[_dataService.dataList objectAtIndex:indexPath.row], @"dataItem", nil];
        [self.navigationController pushViewController:detailVC animated:YES];
    } else   {
        //通知公告
        MyConcernNoticesDetailViewController *detailVC = [[MyConcernNoticesDetailViewController alloc]initWithNibName:@"MyConcernNoticesDetailViewController" bundle:nil];
        detailVC.config = [NSDictionary dictionaryWithObjectsAndKeys:[_dataService.dataList objectAtIndex:indexPath.row], @"dataItem", nil];
        [self.navigationController pushViewController:detailVC animated:YES];
    }

}

#pragma mark - Pull Table Delegate
-(void)customPullToRefreshShouldRefresh:(CustomPullToRefresh *)ptr withDirection:(MSRefreshDirection)direction
{
    [_dataService selectSegmentBarAtIndex:selectIndex == 0 ? 0 : 1];

    NSLog(@"捕获到拉动事件");
    NSArray *array = @[@"1",@"'招标通告','其他通知'",@"'人事招考'",@"'活动预告'"];
    if (direction == MSRefreshDirectionTop) {
        //上拉刷新
        if (selectIndex == 0) {
            [_dataService selectSegmentBarAtIndex:selectIndex];
            [_dataService loadDataWithKey:nil];
            return;
        }
        if (self.searchView.searchText == 0) {
            [_dataService loadNoticeMoreDataWithKey:array[selectIndex] title:nil];
            
        } else {
            [_dataService loadNoticeMoreDataWithKey:array[selectIndex] title:self.searchView.searchText];

        }
    }
    if (direction == MSRefreshDirectionBottom) {
        //下拉获取更多
        if (selectIndex == 0) {
            [_dataService loadNoticeMoreDataWithKey:array[selectIndex] title:nil];

            return;
        }
        if (self.searchView.searchText == 0) {

            [_dataService loadNoticeDataWithKey:array[selectIndex] title:nil];
        } else {
            [_dataService loadNoticeDataWithKey:array[selectIndex] title:self.searchView.searchText];

        }
    }
}


#pragma mark - Data Delegate 
-(void)loadDataFinished
{
    [self stopLoadingView];
    [_ptr endRefresh];
    [_tableView reloadData];
    [_configTableView reloadData];
    if (self.onSaving) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"操作成功" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }
}

-(void)loadDataFaild:(NSString *)msg
{
    [self stopLoadingView];
    [_tableView reloadData];
    [_configTableView reloadData];

    [_ptr endRefresh];
    if (self.onSaving) {
        msg = @"保存定制信息失败";
    }
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"错误" message:msg delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
}

-(void)setEnableToLoadMore:(BOOL)enable
{
    
}

#pragma mark - Save Data
-(void) saveDatas
{
    self.onSaving = YES;
    [self startLoadingViewWithText:@"正在保存..."];
    [_dataService saveMyConcernConfigs];
}
@end
